<!DOCTYPE html>
<html>
    <head>
        <title>Trash Bin</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0 user-scalable=no">
        <link rel="stylesheet" href="../../script/semantic/semantic.min.css">
        <script type="text/javascript" src="../../script/jquery.min.js"></script>
        <script type="text/javascript" src="../../script/semantic/semantic.min.js"></script>
        <script type="text/javascript" src="../../script/ao_module.js"></script>
        <script type="text/javascript" src="../../script/applocale.js"></script>
        <style>
            body{
                background-color:white;
            }
            .banner{
                background-color:#4287f5;
                height:50px;
                padding:12px;
                padding-left:20px;
                padding-top:16px;
            }

            #opricon{
                position:absolute;
                top:0px;
                right:0px;
                width:80px;
                height:80px;
            }
            .title{
                color:white;
                font-size:130%;
            }
            .content{
                padding:12px;
            }
            
            .info{
                margin-top:3px;
                width:80%;
            }
            
        </style>
    </head>
    <body>
        <span class="normalview">
        <div class="ui menu">
            <div class="header item">
               <img class="ui middle aligned mini image" src="trashbin_img/small_icon.png" style="margin-right:8px; height:28px; width:28px;"></img> <span locale="title/title">Trash Bin</span>
            </div>
            <div class="right item">
                <button class="ui negative small button" onclick="clearAll();" locale="button/deleteAll">Delete All</button>
            </div>
        </div>
        <div class="ui container">
            <div class="ui segment">
                <table class="ui celled table">
                    <thead>
                        <tr>
                            <th locale="list/filename">Filename</th>
                            <th locale="list/deleteTime">Delete Time</th>
                            <th locale="list/details">Details</th>
                            <th locale="list/restore">Restore</th>
                        </tr>
                    </thead>
                    <tbody id="trashList">
                    </tbody>
                </table>
                <div class="ui message" id="scanning">
                    <i class="loading spinner icon"></i> <span locale="list/scanning">Scanning for trash in all disks...</span>
                </div>
            </div>
        </div>
        </span>
        <div class="confirmRemove" style="display:none;">
            <div class="banner">
                <div class="title"><span locale="opr/move">Move</span> <span id="fcount">0 File</span> <span locale="opr/toTrashBin">to Trash Bin?</span></div>
                <img id="opricon" src="trashbin_img/trashopr.png" class="ui image"></img>
            </div>
            <div class="content">
                <div class="info"><span locale="opr/delete">Deleting:</span> <span class="filename"></span></div>
                <div style="position:absolute; bottom:8px;right:4px;">
                    <button class="ui small button" onclick="ao_module_close();" locale="opr/cancel">Cancel</button>
                    <button class="ui primary small button" onclick="confirmDelete();" locale="opr/confirm">Confirm</button>
                </div>
            </div>
        </div>
        <div class="ui modal" style="overflow-y:auto; overflow-x:hidden;">
            <i class="close icon"></i>
            <div class="header filename" locale="message/nofileselected">
                No File Selected
            </div>
            <div class="ui basic segment">
                <table class="ui very basic celled table">
                    <thead>
                        <tr>
                            <th locale="message/property">Property</th>
                            <th locale="message/value">Value</th>
                        </tr>
                    </thead>
                    <tbody id="detailList">
                       
                    </tbody>
                </table>
            </div>
            <div class="actions">
                <div class="ui button" onclick=" $('.ui.modal').modal('hide');" locale="detail/ok">
                 OK
                </div>
            </div>
        </div>

        <script>
            var deletePendingFiles = ao_module_loadInputFiles();
            var previousTrashbinFilelist = [];
            var legacyMode = !('WebSocket' in window || 'MozWebSocket' in window); 

            if (!applocale){
                applocale = {
                    init: function(json, callback){
                        if (callback){
                            callback();
                        }
                    }
                }
            }
            applocale.init("../../SystemAO/locale/trashbin.json", function(){
                applocale.translate();

                if (deletePendingFiles != null && deletePendingFiles.length > 0){
                    //Handle trash treatment
                    console.log(deletePendingFiles);
                    ao_module_setFixedWindowSize();
                    //ao_module_setWindowSize(400,200);
                    $(".normalview").hide();
                    $(".confirmRemove").show();

                    //Update graphical information
                    var displayname = deletePendingFiles[0].filename;
                    $("#fcount").text("1 " + applocale.getString("opr/file", "File"));
                    if (deletePendingFiles.length > 1){
                        displayname = displayname + applocale.getString("opr/and", " and ") + (deletePendingFiles.length - 1) + applocale.getString("opr/more", " more");
                        $("#fcount").text(deletePendingFiles.length + " " + applocale.getString("opr/files", "Files"));
                    }
                    $(".filename").text(displayname);

                }else{
                    //List all trash mode
                    ao_module_setWindowSize(1080, 580);
                    initList();
                }

            });

           

            //Initialize the trash list
            function initList(){
                $("#trashList").html("");
                $("#scanning").show();
                if (!legacyMode){
                    //Use WebSocket for rendering
                    var ws = new WebSocket(getWSEndpoint() + `/system/file_system/ws/listTrash`);
                   
                    ws.onopen = function() {
                        previousTrashbinFilelist = [];
                        console.log("TrashBin WebSocket Opened");
                    };
                    
                    ws.onmessage = function (evt) { 
                        var data = evt.data;
                        var thisFile = JSON.parse(data);
                        var filedata = encodeURIComponent(JSON.stringify(thisFile));
                        //console.log(thisFile);

                        $("#trashList").append(`<tr>
                            <td>${thisFile.OriginalFilename}</td>
                            <td>${thisFile.RemoveDate}</td>
                            <td><button filedata="${filedata}" class="ui tiny button" onclick="showDetail(this);">${applocale.getString("button/details","Details")}</button></td>
                            <td><button filedata="${filedata}" class="ui green tiny button" onclick="restore(this);">${applocale.getString("button/restore", "Restore")}</button></td>
                        </tr>`);
                        previousTrashbinFilelist.push(thisFile);
                    };
                    
                    ws.onclose = function() { 
                        console.log("TrashBin WebSocket transfer completed");
                        if (previousTrashbinFilelist.length == 0){
                            $("#trashList").append(`<tr><td colspan="4"><i class="checkmark icon"></i> ${applocale.getString("list/notrash", "There are no files or folders in Trashbin.")}</td></tr>`);
                        }
                        $("#scanning").hide();
                    };

                    ws.onerror = function(){
                        console.log("Open failed. Fallback to legacy mode");
                        legacyMode = true;
                        initList();
                    }
                }else{
                    //Use AJAX (Slower)
                    $.get("../../system/file_system/listTrash",function(data){
                        if (data.error !== undefined){
                            $("#scanning").hide();
                            alert(data.error);
                        }else{
                            previousTrashbinFilelist = [];
                            for (var i =0; i < data.length; i++){
                                var thisFile = data[i];
                                var filedata = encodeURIComponent(JSON.stringify(thisFile));
                                $("#trashList").append(`<tr>
                                    <td>${thisFile.OriginalFilename}</td>
                                    <td>${thisFile.RemoveDate}</td>
                                    <td><button filedata="${filedata}" class="ui tiny button" onclick="showDetail(this);">${applocale.getString("button/details","Details")}</button></td>
                                    <td><button filedata="${filedata}" class="ui green tiny button" onclick="restore(this);">${applocale.getString("button/restore", "Restore")}</button></td>
                                </tr>`);
                                previousTrashbinFilelist.push(thisFile);
                            }

                            if (data.length == 0){
                                $("#trashList").append(`<tr><td colspan="4"><i class="checkmark icon"></i> ${applocale.getString("message/notrash","There are no files or folders in Trashbin.")}</td></tr>`);
                            }
                            $("#scanning").hide();
                        }
                    });
                }
            }

            function getWSEndpoint(){
                //Open opeartion in websocket
                let protocol = "wss://";
                if (location.protocol !== 'https:') {
                    protocol = "ws://";
                }

                var port = window.location.port;
                if (window.location.port == ""){
                    if (location.protocol !== 'https:') {
                        port = "80";
                    }else{
                        port = "443";
                    }
                    
                }

                wsControlEndpoint = (protocol + window.location.hostname + ":" + port);
                return wsControlEndpoint;
            }
            

            //Listen to the change of the trashbin
            setInterval(function(){
                $.get("../../system/file_system/listTrash",function(data){
                    if (data.length != previousTrashbinFilelist.length){
                        //Change of the trashbin file. Update the list
                        initList();
                    }
                });
            }, 30000);

            function showDetail(object){
                var filedata = JSON.parse(decodeURIComponent($(object).attr("filedata")));
                $(".filename").text(filedata.OriginalFilename);
                $("#detailList").html("");
                var keyMapping = {
                    "Filename": applocale.getString("detail/storageFilename", "Storage Filename"),
                    "Filepath": applocale.getString("detail/storageFilepath","Storage Filepath"),
                    "FileExt": applocale.getString("detail/fileExt","File Extension"),
                    "IsDir": applocale.getString("detail/isDir","Is Directory"),
                    "Filesize": applocale.getString("detail/filesize","File Size"),
                    "RemoveTimestamp": applocale.getString("detail/removeTimestamp","Remove Timestamp"),
                    "RemoveDate": applocale.getString("detail/removeDate","Remove Datetime"),
                    "OriginalPath": applocale.getString("detail/originalPath","Original Path"),
                    "OriginalFilename": applocale.getString("detail/originalFilename","Original Filename")
                }
                for (var [key, value] of Object.entries(filedata)) {
                    console.log(key, value);
                    var displayKey = keyMapping[key];
                    if (key == "Filesize"){
                        value = bytesToSize(value);
                    }
                    $("#detailList").append(`<tr>
                            <td>
                                ${displayKey}
                            </td>
                            <td>
                                ${value}
                            </td>
                        </tr>`);
                }
                
                $('.ui.modal').modal('show').css({"overflow-y":"auto","overflow-x": "hidden", "max-height":window.innerHeight - 30 + "px"});

            }

            function bytesToSize(bytes) {
                var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
                if (bytes == 0) return '0 Byte';
                var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
                return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
            }

            function clearAll(){
                if (confirm(applocale.getString("message/confirmDelete", "Confirm deleting ALL FILE PERMANENTLY?"))){
                    $.get("../../system/file_system/clearTrash",function(data){
                        initList();
                    });
                }
            }

            function restore(obj){
                var filedata = JSON.parse(decodeURIComponent($(obj).attr("filedata")));
                var filepath = filedata.Filepath;
                $.ajax({
                    url: "../../system/file_system/restoreTrash",
                    method: "POST",
                    data: {"src" : filepath},
                    success: function(data){
                        if (data.error !== undefined){
                            alert(data.error);
                        }else{
                            initList();
                            parent.refresh(undefined, true);
                        }
                    }
                })
            }

            function confirmDelete(){
                //Confirm delete of the files in the list
                var deleteFileList = [];
                for (var i =0; i <deletePendingFiles.length; i++){
                    deleteFileList.push(deletePendingFiles[i].filepath);
                }
                requestCSRFToken(function(token){
                    $.ajax({
                        url: "../../system/file_system/fileOpr",
                        method:"POST",
                        data: {opr: "recycle", src: JSON.stringify(deleteFileList), csrft: token},
                        success: function(data){
                            if (data.error !== undefined){
                                console.log("Delete failed! " + data.error)
                            }else{
                                //Delete completed. Close this window
                                parent.refresh(undefined, true);
                                ao_module_close();
                            }
                        }
                    });
                });
                
            }

            function requestCSRFToken(callback){
                $.ajax({
                    url: "../../system/csrf/new",
                    success: function(token){
                        callback(token);
                    }
                })
            }
        </script>
    </body>
</html>